package redisUtil

import (
	"MyBlogv2/common/define"
	"MyBlogv2/common/models"
	"context"
	"encoding/json"
	"fmt"
	"strconv"
)

func AddVisitCount(id int) {
	models.RDb.Incr(context.Background(), define.ARTICLE_VISIT_COUNT+strconv.Itoa(id))
}
func AddCommentCount(id int) {
	models.RDb.Incr(context.Background(), define.ARTICLE_COMMENT_COUNT+strconv.Itoa(id))
}
func AddLikeCount(id int) {
	models.RDb.Incr(context.Background(), define.ARTICLE_LIKE_COUNT+strconv.Itoa(id))
}
func AddFavoriteCount(id int) {
	models.RDb.Incr(context.Background(), define.ARTICLE_FAVORITE_COUNT+strconv.Itoa(id))
}
func DelVisitCount(id int) {
	models.RDb.Decr(context.Background(), define.ARTICLE_VISIT_COUNT+strconv.Itoa(id))
}
func DelCommentCount(id int) {
	models.RDb.Decr(context.Background(), define.ARTICLE_COMMENT_COUNT+strconv.Itoa(id))
}
func DelLikeCount(id int) {
	models.RDb.Decr(context.Background(), define.ARTICLE_LIKE_COUNT+strconv.Itoa(id))
}
func DelFavoriteCount(id int) {
	models.RDb.Decr(context.Background(), define.ARTICLE_FAVORITE_COUNT+strconv.Itoa(id))
}
func SaveUserPermission(permissions []string, id int) {
	jsonBytes, err := json.Marshal(permissions)
	if err != nil {
		fmt.Println("json.Marshal with error: %+v\n", err)
	}
	models.RDb.Set(context.Background(), define.USER_PERMISSION_KEY+strconv.Itoa(id), jsonBytes, 0)

}

func GetUserPermission(id int) ([]string, int) {
	var permissions []string
	exists := models.RDb.Exists(context.Background(), define.USER_PERMISSION_KEY+strconv.Itoa(id))
	result, _ := models.RDb.Get(context.Background(), define.USER_PERMISSION_KEY+strconv.Itoa(id)).Result()
	json.Unmarshal([]byte(result), &permissions)
	return permissions, int(exists.Val())
}
func DelUserPermission(id int) {
	models.RDb.Del(context.Background(), define.USER_PERMISSION_KEY+strconv.Itoa(id))
}

func GetWebsiteWordCount() (int, error) {
	result, err := models.RDb.Get(context.Background(), define.WEBSITE_WORD_COUNT).Result()
	if err != nil {
		return 0, err
	}
	wordCount, err := strconv.Atoi(result)
	if err != nil {
		return 0, err
	}
	return wordCount, nil
}

func SetWebsiteWordCount(count int) error {
	return models.RDb.Set(context.Background(), define.WEBSITE_WORD_COUNT, count, 0).Err()
}

func IncrWebsiteWordCount(increment int) {
	models.RDb.IncrBy(context.Background(), define.WEBSITE_WORD_COUNT, int64(increment))
}

func DecrWebsiteWordCount(decrement int) {
	models.RDb.DecrBy(context.Background(), define.WEBSITE_WORD_COUNT, int64(decrement))
}
